package com.example.springdemo.datasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源切换的AOP
 *
 * @author wanghuajun
 * @version 1.0
 * @date 2019-08-09 21:50
 */
@Slf4j
@Aspect
@Component
@ConditionalOnProperty(prefix = "multiple-db", name = "datasource-open", havingValue = "true")
//当配置文件中multiple-db开头的datasource-open的值为true的时候，该注解才生效
public class MultipleDataSourceAop implements Ordered {

    /**
     * aop的顺序要早于spring的事物
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }

    @Around("@annotation(com.example.springdemo.datasource.DataSource)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("执行MultipleDataSourceAop");

        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = null;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("@DataSource注解只能用于方法上！");
        }
        methodSignature = (MethodSignature) signature;

        Object target = joinPoint.getTarget();
        Method method = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());

        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (null != dataSource) {
            DataSourceContextHolder.setDataSourceType(dataSource.name());
            log.info("设置数据源为----------->【dataSource:{}】", dataSource.name());
        } else {
            DataSourceContextHolder.setDataSourceType(DB.USER_CENTER);
            log.info("设置数据源为----------->【dataSource:{}】", DB.USER_CENTER);
        }

        try {
            return joinPoint.proceed();
        } finally {
            log.info("接口请求完毕，清空数据源信息！");
            DataSourceContextHolder.clearDataSourceType();
        }
    }

}
